<script setup lang="ts">
import type { UploadFile } from 'element-plus'
import type { ResWrapper } from '@/apis/common/commonApi'
import { computed, onMounted, watch } from 'vue'
import { sysFileApi } from '@/apis/system/sysFileApi'
import { useLoginStore } from '@/stores/loginStore'

const { groupName } = defineProps<{
  groupName: string
}>()

const emits = defineEmits(['success'])

const model = defineModel<number>()
const fileUrl = defineModel<string>('fileUrl')

const loginStore = useLoginStore()

onMounted(initFileUrl)
watch(() => model.value, initFileUrl)

async function initFileUrl() {
  if (model.value && !fileUrl.value) {
    const data = await sysFileApi.findDetail(model.value)
    fileUrl.value = data.fileUrl
  }
}

const uploadInfo = computed(() => {
  return {
    action: `${import.meta.env.VITE_API_BASE_URL}/system/file/upload/${groupName}`,
    headers: { 'Authorization': `Bearer ${loginStore.user.token}`, 'app-type': 'MANAGE', 'app-ver': import.meta.env.VITE_APP_VERSION },
  }
})

function onUploadSuccess(response: ResWrapper<any>, uploadFile: UploadFile) {
  if (!response.success) {
    ElMessage.error(`${response.errCode}-${response.errMsg}`)
    uploadFile.status = 'fail'
  }
  model.value = response.data.id
  fileUrl.value = response.data.fileUrl
  emits('success')
}
</script>

<template>
  <el-upload
    :action="uploadInfo.action"
    :on-success="onUploadSuccess"
    :headers="uploadInfo.headers"
    :show-file-list="false"
    crossorigin="use-credentials"
  >
    <slot :file-url="fileUrl" />
  </el-upload>
</template>
